package com.qianfeng.smartmeeting.controller;

import com.qianfeng.smartmeeting.entity.UserEntity;
import com.qianfeng.smartmeeting.service.LoginService;
import com.qianfeng.smartmeeting.util.JwtUtil;
import com.qianfeng.smartmeeting.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/smartmeeting")
public class LoginController {

    @Autowired
    private LoginService loginService;

    @Autowired
    private AuthenticationManager authenticationManager;

    @RequestMapping("/login")
    public R login(String username, String password){
        try {
            // 1. 调用Spring Security认证
            Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(username, password)
            );

            // 2. 认证成功，生成JWT
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            UserEntity user = loginService.findByUserName(username);
            Map<String, Object> claims = new HashMap<>();
            claims.put("userId", user.getUserId());
            claims.put("username", user.getUserName());
            claims.put("userRole", user.getUserType() == 1 ? "ADMIN" : "USE R");

            String token = JwtUtil.genToken(claims);
            return R.ok("登录成功!").setData(token);
        } catch (Exception e) {
//            log.error("认证失败：未知错误", e);
            return R.error("登录失败，请重试");
        }
    }

    @RequestMapping("/register")
    public R register(String username, String password){
        UserEntity registerUser = loginService.findByUserName(username);
        UserEntity user = new UserEntity();

        if(registerUser != null){
            //此用户已存在
            return R.error("用户已存在，请更换用户名");
        }
        user.setUserName(username);
        user.setUserPassword(password);
        //进行注册
        loginService.register(user);

        return R.ok("注册成功!");
    }
}
